import React, { useEffect, useRef, useState } from 'react';
import { Factory } from 'vexflow';

import { Voice, Stave, StaveNote, Beam, Formatter, Renderer, Accidental, Dot, EasyScore, TickContext } from 'vexflow';
import RoundBackground from './RoundBackground';

export const Note = () => {
    const sheetMusicRef = useRef(null);
    const [notePositions, setNotePositions] = useState([]);

    const positions = [];
    useEffect(() => {
        if (!sheetMusicRef.current) return;
        sheetMusicRef.current.innerHTML = '';

        try {
            const vf = new Factory({
                renderer: {
                    elementId: 'sheet-music',
                    width: 800,
                    height: 270,
                },
            });

            const score = vf.EasyScore();
            const context = vf.getContext();

            // 绘制小节
            drawMeasure(context, score, 'b4/8, b4/8, b4/8, b4/8, b4/8, b4/8, b4/8, b4/8', 0);
            drawMeasure(context, score, 'b4/8, b4/8, b4/8, b4/8, b4/8, b4/8, b4/8, b4/8', 1);
            drawMeasure(context, score, 'b4/8, b4/8, b4/8, b4/8, b4/8, b4/8, b4/8, b4/8', 2);
            drawMeasure(context, score, 'b4/4, b4/4, b4/8, b4/8, b4/8, b4/8', 3);



            // setNotePositions(positions);
        } catch (error) {
            console.error('Error initializing VexFlow:', error);
        }
    }, []);


    function drawMeasure(context, score, notesString, measureIndex, width = 300, lineHeight = 150) {
        // 每行小节的数量
        const measuresPerLine = 2; // 每行显示两个小节
        const x = (measureIndex % measuresPerLine) * (width); // 计算 x 坐标
        const y = Math.floor(measureIndex / measuresPerLine) * lineHeight; // 计算 y 坐标

        // 创建小节
        const stave = new Stave(x, y, width);
        stave.setContext(context).draw();

        // 创建音符
        const notes = score.notes(notesString);

        // 每小节分为16份，计算每个音符的位置
        let currentX = x;

        notes.forEach((note, index) => {
            const color = 'rgba(255, 0, 0, 0.0)' // 偶数索引设置为红色，奇数索引设置为蓝色
            note.setStyle({ fillStyle: color, strokeStyle: color });  // 设置音符的填充和描边颜色

        });

        // 计算并绘制连音线（如果有）
        const beams = Beam.generateBeams(notes);


        Formatter.FormatAndDraw(context, stave, notes);
        // const formatter = new Formatter();
        // formatter.format(notes, stave.getWidth());

        let poses = calculateNotePositions(notes);
        console.log(poses)

        notes.forEach((note, index) => {
            const color = 'black' // 偶数索引设置为红色，奇数索引设置为蓝色
            note.setStyle({ fillStyle: color, strokeStyle: color });  // 设置音符的填充和描边颜色
        });
        poses.forEach(pos => {
            let note = pos.note;
            var tc = new TickContext()
            tc.setX(calculateNoteXPosition(pos.startPosition))
            // tc.set
            note.setTickContext(tc).draw()
            }
        )

        // notes.forEach((note) => {
        //     const bbox = note.getBoundingBox();
        //     const containerRect = document.getElementById('sheet-music').getBoundingClientRect();
        //
        //     if (bbox) {
        //         const absoluteX = bbox.getX() + containerRect.left;
        //         const absoluteY = containerRect.top+Math.floor(measureIndex / measuresPerLine)*140+80;
        //         positions.push({ x: absoluteX, y: absoluteY });
        //     }
        // });
        // console.log(positions);

        beams.forEach(beam => beam.setContext(context).draw());
    }

    function calculateNotePositions(notes) {
        const totalTicks = 16;  // 总共有 16 单位位置（4拍）
        let totalDuration = 0;  // 用来记录音符时值总和
        const notePositions = [];

        // 1. 计算所有音符的时值总和
        notes.forEach(note => {
            const duration = note.getDuration();
            totalDuration += convertDurationToTicks(duration);  // 将音符时值转换为ticks
        });

        // 2. 确保时值总和等于4拍（16单位）
        if (totalDuration !== totalTicks) {
            console.warn(`Total duration of notes is ${totalDuration}, but it should be 16 ticks.`);
            // 这里可以根据需求做一些调整，例如填充或改变音符的时值
        }

        // 3. 根据每个音符的时值计算其在小节中的位置
        let currentPosition = 0;
        notes.forEach(note => {
            const duration = note.getDuration();
            const ticks = convertDurationToTicks(duration);  // 将时值转换为ticks
            notePositions.push({
                note,
                startPosition: currentPosition,
                duration: ticks
            });
            currentPosition += ticks;  // 更新当前音符的结束位置
        });



        return notePositions;
    }

    // Convert note duration to ticks based on its fraction (1/4, 1/8, etc.)
    function convertDurationToTicks(duration) {
        const durationMap = {
            'w': 16,   // 全音符
            'h': 8,    // 半音符
            '4': 4,    // 四分音符
            '8': 2,    // 八分音符
            '16': 1    // 十六分音符
        };

        // const noteValue = duration.charAt(1); // 假设时值是类似"c4/8"的格式
        return durationMap[duration] || 0; // 如果没有找到对应的时值，默认为0
    }

    function calculateNoteXPosition(startPosition, totalTicks = 16, measureWidth = 300) {
        return (startPosition / totalTicks) * measureWidth;
    }


    function generateNotePositions() {
        setNotePositions([
            {
                "x": 94.50511056594848,
                "y": 180.03378295898438
            },
            {
                "x": 178.5216105659485,
                "y": 175.03378295898438
            },
            {
                "x": 262.53811056594844,
                "y": 170.03378295898438
            },
            {
                "x": 346.55461056594845,
                "y": 160.03378295898438
            }
        ]);
    }

    function generateNotePositions2() {
        setNotePositions(positions);
    }

    return (
        <div className="py-8 text-base leading-6 space-y-4 text-gray-700 sm:text-lg sm:leading-7">
            <h1 className="text-2xl font-bold mb-8 text-center">Rhythm Trainer</h1>
            <div id="sheet-music" ref={sheetMusicRef} className="relative border rounded p-4 mb-8 mx-auto"
                style={{ width: '800px', position: 'relative' }}>
            </div>
            {/* 按钮，用来触发 generateNotePositions 函数 */}
            <button
                onClick={generateNotePositions}
                className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-700"
            >
                Generate Notes
            </button>

            <button
                onClick={generateNotePositions2}
                className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-700"
            >
                Generate Notes
            </button>

            <RoundBackground positions={notePositions} />
        </div>
    );
};
